//
//  CameraView.m
//  webApp
//
//  Created by 黄晓容 on 16/5/29.
//  Copyright © 2016年 cloud. All rights reserved.
//

#import "CameraView.h"

#import "UIImage+Resize.h"

#import <AVFoundation/AVFoundation.h>

@interface CameraView()

@property (nonatomic, retain) AVCaptureSession *session;
@property (nonatomic, retain) AVCaptureDeviceInput *input;
@property (nonatomic, retain) AVCaptureDevice *device;
@property (nonatomic, retain) AVCaptureStillImageOutput *imageOutput;
@property (nonatomic, retain) AVCaptureVideoPreviewLayer *preview;

@end

@implementation CameraView

-(instancetype)initWithFrame:(CGRect)frame positionDevice:(CameraType)position {
    if (self = [super initWithFrame:frame]) {
        [self initCameraInPosition:position];
    }
    return self;
}

-(void)initCameraInPosition:(CameraType)position{
    self.session = [AVCaptureSession new];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    NSArray *devices = [NSArray new];
    devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (position == CameraTypePostposition) {
            if ([device position] == AVCaptureDevicePositionBack) {
                _device = device;
                break;
            }
        }else {
            if ([device position] == AVCaptureDevicePositionFront) {
                _device = device;
                break;
            }
        }
    }
    
    NSError *error;
    
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    self.imageOutput = [AVCaptureStillImageOutput new];
    NSDictionary *outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
    [self.imageOutput setOutputSettings:outputSettings];
    [self.session addOutput:self.imageOutput];
    self.preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [self.preview setVideoGravity:AVLayerVideoGravityResizeAspect];
    [self.preview setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self.layer addSublayer:self.preview];
    [self.session startRunning];
    
}

-(void)capturePhoto:(void (^)(UIImage *image))completionBlock
{
    if (self.imageOutput != nil) {
        AVCaptureConnection *videoConnection = nil;
        for (AVCaptureConnection *connection in self.imageOutput.connections) {
            for (AVCaptureInputPort * port in connection.inputPorts) {
                if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                    videoConnection = connection;
                    break;
                }
            }
            if (videoConnection) { break; }
        }
        
        [self.imageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
          completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
              NSData *ImageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
              UIImage *image = [UIImage imageWithData:ImageData];
              UIImage *imageToDisplay = [UIImage imageWithCGImage:[image CGImage] scale:1.0 orientation:UIImageOrientationUp];
              imageToDisplay = [imageToDisplay rotatedByDegrees:90]; //拍摄照片会向左横屏，向右旋转90度
              completionBlock(imageToDisplay);
              
          }];
    }
}

@end
